package com.baidu.bos.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.baidu.bos.domain.Region;
import com.baidu.bos.domain.Subarea;
import com.baidu.bos.service.IRegionService;
import com.baidu.bos.service.ISubareaService;
import com.baidu.bos.utils.FileUtils;
import com.baidu.bos.utils.PinYin4jUtils;
import com.baidu.bos.web.action.base.BaseAction;

@Controller
@Scope("prototype")
public class SubareaAction extends BaseAction<Subarea> {
	@Resource
	private ISubareaService subareaService;
	@Resource
	private IRegionService regionService;
	/**
	 * 保存分区
	 * @return
	 */
	public String save(){
		subareaService.save(model);
		return "list";
	}
	
	
	private File myFile;
	private String myFileFileName;
	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}
	public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}
	/**
	 * 导入分区数据
	 * @throws IOException 
	 */
	public String upload() throws IOException{
		String flag = "1";// 导入是否成功的标识
		// 创建一个List对象，包装区域对象
		List<Subarea> list = new ArrayList<Subarea>();
		try {
			Workbook workbook = null;
			if (myFileFileName.endsWith(".xls")) {
				//1.加载xls文件
				workbook = new HSSFWorkbook(
						new FileInputStream(myFile));
			}else if(myFileFileName.endsWith(".xlsx")){
				//加载xlsx文件
				workbook = new XSSFWorkbook(
						new FileInputStream(myFile));
			}
			//获取第一个sheet
			Sheet sheet = workbook.getSheetAt(0);
			for (Row row : sheet) {
				int rowNum = row.getRowNum();
				if (rowNum == 0) {
					// 第一行为文件的标题行，忽略
					continue;
				}
				String id = row.getCell(0).getStringCellValue();
				String regionId = row.getCell(1).getStringCellValue();
				String addresskey = row.getCell(2).getStringCellValue();
				String startnum = row.getCell(3).getStringCellValue();
				String endnum = row.getCell(4).getStringCellValue();
				String single = row.getCell(5).getStringCellValue();
				String position = row.getCell(6).getStringCellValue();
				
				Region region = regionService.findById(regionId);
				//Region region = new Region(regionId);
				Subarea subarea = new Subarea(id, region, addresskey, startnum, endnum,single,position);
				
				list.add(subarea);
			}
			//批量保存数据
			subareaService.saveBatch(list);
		} catch (Exception e) {
			e.printStackTrace();
			flag = "0";
		}
		ServletActionContext.getResponse().getWriter().print(flag);
		return NONE;
	}
	
	/**
	 * 查询所有区域
	 */
	public String pageQuery(){
		String addresskey = model.getAddresskey();
		//获取region对象
		Region region = model.getRegion();
		//获取DetachedCriteria对象
		DetachedCriteria subareaDC = pageBean.getDetachedCriteria();
		if (StringUtils.isNotBlank(addresskey)) {
			subareaDC.add(Restrictions.like("addresskey", "%"+addresskey+"%"));
		}
		
		if (region != null) {
			subareaDC.createAlias("region", "r");
			String province = region.getProvince();
			String city = region.getCity();
			String district = region.getDistrict();
			if (StringUtils.isNotBlank(province)) {
				subareaDC.add(Restrictions.like("r.province", "%"+province+"%"));
			}
			if (StringUtils.isNotBlank(city)) {
				subareaDC.add(Restrictions.like("r.city", "%"+city+"%"));
			}
			if (StringUtils.isNotBlank(district)) {
				subareaDC.add(Restrictions.like("r.district", "%"+district+"%"));
			}
		}
		subareaService.pageQuery(pageBean);
		//将pageBean转化为json对象
		this.writeObject2Json(pageBean);
		return NONE;
	}
	/**
	 * 将分区数据到出为xls文件
	 * @throws IOException 
	 */
	public String exportXls() throws IOException{
		//查询所有数据
		List<Subarea> list = subareaService.findAll();
		//将list数据写入到一个xls文件中
		HSSFWorkbook workbook = new HSSFWorkbook();
		//创建一个sheet
		HSSFSheet sheet = workbook.createSheet("分区数据");
		//创建标题行
		HSSFRow row = sheet.createRow(0);
		row.createCell(0).setCellValue("分区编号");
		row.createCell(1).setCellValue("区域编码");
		row.createCell(2).setCellValue("关键字");
		row.createCell(3).setCellValue("起始号");
		row.createCell(4).setCellValue("结束号");
		row.createCell(5).setCellValue("单双号");
		row.createCell(6).setCellValue("位置信息");
		for (Subarea subarea : list) {
			HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
			dataRow.createCell(0).setCellValue(subarea.getId());
			dataRow.createCell(1).setCellValue(subarea.getRegion().getId());
			dataRow.createCell(2).setCellValue(subarea.getAddresskey());
			dataRow.createCell(3).setCellValue(subarea.getStartnum());
			dataRow.createCell(4).setCellValue(subarea.getEndnum());
			dataRow.createCell(5).setCellValue(subarea.getSingle());
			dataRow.createCell(6).setCellValue(subarea.getPosition());
		}
		ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();
		String filename = "分区数据.xls";
		filename = FileUtils.encodeDownloadFilename(filename,
				ServletActionContext.getRequest().getHeader("user-agent"));
		
		ServletActionContext.getResponse().setContentType(
				ServletActionContext.getServletContext().getMimeType(filename));

		ServletActionContext.getResponse().setHeader("content-disposition",
				"attachment;filename=" + filename);
		workbook.write(out);
		return NONE;
	}
	/**
	 * 查询所有未关联定区的分区
	 */
	public String findSubareaByAjax(){
		DetachedCriteria dc = DetachedCriteria.forClass(Subarea.class);
		dc.add(Restrictions.isNull("decidedzone"));
		List<Subarea> list = subareaService.findByCondition(dc);
		this.writeObject2Json(list);
		return NONE;
	}
}
